package 极客算法训练营.chapter06;

import java.util.ArrayList;
import java.util.List;

public class N叉树的层级遍历 {

    class Node {
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    class Solution {
        private List<List<Integer>> res = new ArrayList<>();
        public List<List<Integer>> levelOrder(Node root) {
            if (root == null) return res;
            recursionTree(root, 0);
            return res;
        }

        public void recursionTree(Node node, int level) {
            //准备空间
            if (res.size() <= level) {
                res.add(new ArrayList<>());
            }
            //进行本次递归的操作
            res.get(level).add(node.val);
            //递归终止条件
            if (node.children.isEmpty()) return;
            //下次递归操作
            for (Node child : node.children) {
                recursionTree(child, level + 1);
            }
        }
    }
}
